import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CommentData } from './dto/comment.entity';

@Injectable()
export class CommentService {
  constructor(
    @InjectRepository(CommentData)
    private readonly commentService: Repository<CommentData>,
  ) {}

  async getCommentContent(noteId: string): Promise<CommentData[]> {
    const result = await this.commentService.find({
      select: ['content', 'commentUserName', 'createTime', 'alias', 'avatar'],
      where: { commentNoteId: noteId },
    });
    return result;
  }

  async createCommentContent(comment: any, user: any): Promise<CommentData> {
    const commentData = new CommentData();
    commentData.content = comment.content;
    commentData.commentNoteId = comment.noteId;
    commentData.commentUserId = user.id;
    commentData.commentUserName = user.username;
    commentData.alias = comment.alias;
    commentData.createTime = comment.createTime;
    commentData.avatar = comment.avatar;
    const result = await this.commentService.save(commentData);
    if (result) {
      return result;
    }
  }

  async deleteCommentContent(commentId: string): Promise<any> {
    const commentData = await this.commentService.find({
      where: { commentNoteId: commentId },
    });
    if (commentData.length > 0) {
      commentData.forEach(async (item) => {
        await this.commentService.delete(item.id);
      });
    }
  }
}
